package cn.itsource.basic.controller;

import cn.hutool.core.io.FileUtil;
import cn.itsource.basic.util.JsonResult;
import cn.itsource.basic.util.PetConstant;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/file")
public class FileController {
    @RequestMapping("/ossUpload")
    public JsonResult ossUpload(@RequestParam("file") MultipartFile file) throws Exception {
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = PetConstant.END_POINT;
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = PetConstant.ACCESS_KEY_ID;
        String accessKeySecret = PetConstant.ACCESS_KEY_SECRET;
        // 填写Bucket名称，例如examplebucket。
        String bucketName = PetConstant.BUCKET_NAME;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            //1.不能重复 (时间戳) , 后缀不能变  //shayu.png
            //file.getOriginalFilename()  :shayu.png //返回png
            String objectName = System.currentTimeMillis()+"."+FileUtil.getSuffix(file.getOriginalFilename());

            // 创建PutObject请求。
            ossClient.putObject(bucketName, objectName, file.getInputStream());
            //https://fengchuqiang.oss-cn-hangzhou.aliyuncs.com/1665910562056.jpg
            String url = "https://"+bucketName+"."+endpoint+"/"+objectName;
            return JsonResult.createSuccess("成功",url);

        } catch (Exception oe) {
            oe.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        return JsonResult.createError("oss上传失败");
    }
}
